#include "Mesh.h"
#include "Resource.h"

namespace Resource
{
	static Mesh* loadMeshBIN(const char *name);
	
	Mesh* loadMesh(const char *name)
	{
		ASSERT(name);
		
		const char *ext = strrchr(name, '.');
		if (!ext)
		{
			LOG_ERROR("Invalid mesh '%s' extension\n", name);
			return NULL;
		}
		
		if (strcmp(ext, ".bin") == 0)
			return loadMeshBIN(name);
		
		LOG_ERROR("Not supported mesh '%s' extension '%s'\n", name, ext);
		return NULL;
	}
	
	static Mesh* loadMeshBIN(const char *name)
	{
		ASSERT(name);
		
		File *file = loadFile(name);
		if (file == NULL)
			return NULL;
		
		if (file->size < sizeof(MeshHead))
		{
			LOG_ERROR("Model '%s' size is too small\n", name);
			freeFile(file);
			return NULL;
		}
		
		MeshHead *head = (MeshHead *)file->data;
		Mesh     *mesh = new Mesh(head->head.vcount, head->head.icount);
		memcpy(mesh, head, sizeof(MeshHead));
		
		const Vertex   *vdata = (const Vertex *)(file->data + sizeof(MeshHead));
		const uint32_t *idata = (const uint32_t *)(file->data + sizeof(MeshHead) + head->head.vcount * sizeof(Vertex));
		
		memcpy(mesh->vdata, vdata, head->head.vcount * sizeof(Vertex));
		memcpy(mesh->idata, idata, head->head.icount * sizeof(uint32_t));
		
		freeFile(file);
		return mesh;
	}
}
